package inc.jmc.cyberboard.chat;
/*
 * IncomingMessagesThread.java
 *
 * Created on 5 de octubre de 2006, 10:48 AM
 *
 
 */
import inc.jmc.cyberboard.common.NumFormat;
import inc.jmc.cyberboard.ui.CyberManager;

import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.util.Date;
import java.util.StringTokenizer;

import javax.swing.JInternalFrame;

import org.apache.log4j.Logger;
/**
 *
 * @author Juan Miguel Olguin Salguero
 *
 **TEXTO DE INFORMACION PARA EL BLOQUEO DE LOS mensages de entrada
 *Set your firewall to block UDP and TCP ports 135, 137-139, and port 445 from all incoming requests or data.
 *A reboot may be required for changes to take effect depending on your firewall software.
 *Please Note: That while blocking UDP and TCP ports 135, 137-139 and 445 will prevent 
 * the webpopup spam from reaching you, it may also block such programs such as Microsoft Outlook 
 * which use port 135 to communicate. If you discover certain software fails to work after blocking the ports 
 * mentioned above, most firewall software allows the user to designate certain software for pass-through access. 
 * This must be set manually by the user. Please see your firewall's help section to learn how to do this.
 *
 *
 *
 */
public class IncomingMessagesThread extends Thread {
    
	public static  int LISTENING_PORT=12259;
	//public static final int SENDING_PORT=65001;
	
    static Logger logger = Logger.getLogger(IncomingMessagesThread.class.getName());
	
    private CyberManager cyberM;
    int port;
    InetAddress localAddress;
    public static InetAddress getInetAddressFromStringIP(String ip)
    {
        InetAddress iaddr=null;
        StringTokenizer st=new StringTokenizer(ip,".");
        try{
                iaddr=InetAddress.getByAddress(
                    new byte[]{(byte)Integer.parseInt(st.nextToken()),
                               (byte)Integer.parseInt(st.nextToken()),
                               (byte)Integer.parseInt(st.nextToken()),
                               (byte)Integer.parseInt(st.nextToken())
                              });
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return iaddr;
    }
    public IncomingMessagesThread(CyberManager cns,int port )throws Exception {
        this.cyberM=cns;
        this.port=port;
        
        localAddress=InetAddress.getLocalHost();
        logger.debug("puerto:"+this.port);
        logger.debug("inetaddress:"+this.localAddress);
                
    }
    boolean escucho=true;
    public void stopListening()
    {
        escucho=false;
    }
    public String prepareHtmlColors(String nick1,String mensaje)
    {
    	String hora = NumFormat.sdf_hh_mm_ss.format(new Date());
    	String preparedtxt="<font color=\"#0000FF\" size=\"3\" face=\"Arial, Helvetica, sans-serif\">[<strong>"+hora+"</strong>(&lt;o&gt;)<strong>"+nick1+"</strong>] : </font><font color=\"#CC00CC\" size=\"3\" face=\"Arial, Helvetica, sans-serif\"><strong>"+mensaje+"</strong></font><br>";
    	return preparedtxt;
    }
    public void run() {
             
        try{
            logger.debug("Thread iniciado y corriendo");
            ServerSocket socketRecept=null;
            try{
            socketRecept=new ServerSocket(port) ;
            }
            catch(java.net.BindException ex){
                port+=10;
                socketRecept=new ServerSocket(port) ;
                
            }
            
            logger.info("Nos pudimos conectar al puerto "+(port));
            logger.debug("Ahora esperando que se haga una conexion...");
            while(escucho)
              {
                int car=12;
                Socket inSocket=socketRecept.accept();
                logger.debug("se hizo una conexion");
                java.io.InputStream is=inSocket.getInputStream();
                StringBuffer sb=new StringBuffer();
                while((car=is.read())!=-1)
                {
                    sb.append((char)car);
                } 
                String ip1aux=inSocket.getInetAddress().toString().split("/")[1];
                //String linereceived="["+ip1aux+"]:  "+sb;
                String linereceived=this.prepareHtmlColors(ip1aux, sb.toString());
                ChatFrm chatFrmOrigen = getChatFrmOrigen(ip1aux);
                if(chatFrmOrigen==null)
                	chatFrmOrigen = this.createChatFrm(ip1aux);
                //TODO String auxt=chatFrmOrigen.getAllChatTxt().getText();
                String wrapptxt=chatFrmOrigen.allChatTxtContent.append(linereceived).toString();
                chatFrmOrigen.getAllChatTxt().setText(wrapptxt);
                logger.info("TEXTO PARA JEDITORPANE:"+wrapptxt);
                  //TODO String text1=chatFrmOrigen.getAllChatTxt().getText();
                  chatFrmOrigen.getAllChatTxt().setCaretPosition(chatFrmOrigen.calcPositionCaret(chatFrmOrigen.getAllChatTxt()));
                chatFrmOrigen.getJPanel1().updateUI();
                logger.debug("--socket leido--");
                logger.debug("--socket leido--");
                is.close();
                inSocket.close();
              }
            
            logger.debug("El threar "+this.getName()+" ya dejo de atender peticiones");
        }
        catch(Exception ex)
              {
                ex.printStackTrace();
              }
         }
    
    public ChatFrm createChatFrm(String ip) {

    	String ip1 = ip;
    	ChatFrm chat=new ChatFrm();
    	chat.setTitle("Chat con: "+ip1+"/");
    	chat.getDestinoTxt().setText(ip1);
    	chat.getNickTxt().setText("");
    	
        
        try {
        	cyberM.getJDesktopPane2().add(chat);
        	chat.setSelected(true);
        	chat.setClosable(true);
            chat.setResizable(true);
            cyberM.getJDesktopPane2().setSelectedFrame(chat);
            chat.toFront();
            chat.setVisible(true);
            cyberM.getJDesktopPane2().updateUI();
            logger.info("cyberM.getJDesktopPane2().updateUI();");
        } catch (java.beans.PropertyVetoException e) 
        {
            e.printStackTrace();
        }
        return chat;
    }
    public ChatFrm getChatFrmOrigen(String ip)
    {
    	ChatFrm ret=null;
    	JInternalFrame[] frames=cyberM.getJDesktopPane2().getAllFrames();
        for(int i=0;i<frames.length;++i)
        {
            if(frames[i].getClass().getName().indexOf("ChatFrm")>=0)
            {
            	ChatFrm chatfrm1=(ChatFrm)frames[i];
            	String ipcomp=chatfrm1.getDestinoTxt().getText();
            	if(ipcomp.equals(ip))
            	{
            		ret=chatfrm1;
            		break;
            	}
            }
        }
        return ret;
    	
    	
    }
}
